package com.ebt.m.customer.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.widgets.BaseRxActivity;
import com.ebt.m.customer.model.CustomerModelNew;
import com.ebt.m.customer.net.json.CustomerSearchListJson;
import com.ebt.m.customer.util.CustomerConvertUtil;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.customer.view.CustomerItemSearchView;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.homepage.CustomerEvent;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.view.ClearEditText;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class ActivityCustomerSearch extends BaseRxActivity {

    //views
    private ClearEditText mSearchView;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        initValues();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void initViews() {
        setContentView(R.layout.activity_customer_search);
        mSearchView = (ClearEditText) this.findViewById(R.id.et_search);
        mRecyclerView = (RecyclerView) this.findViewById(R.id.rv);
        if (mLinearLayoutManager == null) {
            mLinearLayoutManager = new LinearLayoutManager(this);
        }
        mRecyclerView.setLayoutManager(mLinearLayoutManager);

        if (mAdapter == null) {
            mAdapter = new AdapterForSearchCustomer(this, mCustomerModelNews);
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    public void initValues() {
        RxView.clicks(findViewById(R.id.btn_cancel))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    onBackPressed();
                });
        RxView.clicks(findViewById(R.id.btn_search))
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    mShowToast = true;
                    search(mSearchView.getText().toString().trim());
                    TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_CUSTOMER_SEARCH);
                });
    }

    private boolean mShowToast = true;

    private void search(String keyWords) {
        if (keyWords == null || keyWords.trim().length() == 0) {
            if (mShowToast) {
                ToastUtil.showToast("请输入搜索关键字");
            }
        } else {
            if (NetUtils.isNetworkConnected(this)) {
                EBTAPI ebtapi = AppInitService.getEbtApi();
                ebtapi.searchCustomerByName(keyWords).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerListSubscriber());
            } else {
                ToastUtil.showToast(getString(R.string.network_fail));
            }
        }
    }

    private Observer<CustomerSearchListJson> getCustomerListSubscriber() {
        return new Observer<CustomerSearchListJson>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onComplete() {
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(mShowToast, "没有搜索到客户");
            }

            @Override
            public void onNext(CustomerSearchListJson customerSearchListJson) {
                if (customerSearchListJson == null) {
                    ToastUtil.showToastD(mShowToast, "获取的搜索数据为空");
                    return;
                }
                if (customerSearchListJson.error != null) {
                    ToastUtil.showToast(mShowToast, "获取搜索列表出错 \n" + "出错代码为:" + customerSearchListJson.error.message);
                    return;
                }
                if (customerSearchListJson.error == null) {
                    if (customerSearchListJson.data == null) {
                        ToastUtil.showToastD(mShowToast, "获取搜索列表为空");
                        return;
                    } else {
                        showSearchList(customerSearchListJson);
                    }
                }
            }
        };
    }

    private ArrayList<CustomerModelNew> mCustomerModelNews = new ArrayList();
    private AdapterForSearchCustomer mAdapter;

    private void showSearchList(CustomerSearchListJson customerSearchListJson) {
        List<CustomerModelNew> list = new ArrayList<>();
        if (customerSearchListJson.data != null) {
            list = CustomerConvertUtil.convertCustomerListToCustomerModelNewList(customerSearchListJson.data);
        }
        mCustomerModelNews.clear();
        mCustomerModelNews.addAll(list);
        mAdapter.notifyDataSetChanged();
        if (list == null || list.size() == 0) {
            ToastUtil.showToast(mShowToast, "没有搜索到客户");
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }

    class AdapterForSearchCustomer extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private Context context;
        private List<CustomerModelNew> customerModelNews;

        public AdapterForSearchCustomer(Context context, List<CustomerModelNew> customerModelNews) {
            this.context = context;
            this.customerModelNews = customerModelNews;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new SearchViewHolder(createView());
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            CustomerItemSearchView searchView = (CustomerItemSearchView) holder.itemView;
            searchView.update(customerModelNews.get(position));
        }

        @Override
        public int getItemCount() {
            return customerModelNews.size();
        }

        public View createView() {
            return new CustomerItemSearchView(context);
        }

        class SearchViewHolder extends RecyclerView.ViewHolder {
            public SearchViewHolder(View itemView) {
                super(itemView);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(CustomerEvent event) {
        mShowToast = false;
        search(mSearchView.getText().toString().trim());
    }
}
